package servicediscovery;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.impl.ConcurrentHashSet;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.servicediscovery.Record;
import io.vertx.servicediscovery.ServiceDiscovery;
import io.vertx.servicediscovery.ServiceDiscoveryOptions;
import io.vertx.servicediscovery.types.HttpEndpoint;

import java.util.Set;

/**
 * @Author Ldj
 * @Date 2017/11/1 13:46
 * @Description 服务发现注册类
 */
public class ServiceDiscoveryVerticle extends AbstractVerticle {

    private static final Logger logger = LoggerFactory.getLogger(ServiceDiscoveryVerticle.class);

    protected ServiceDiscovery discovery;

    public Set<Record> registeredRecords = new ConcurrentHashSet<>();

    public Future<Void> publishHttpEndpoint(String name, String host, int port,String root) {
        Record record = HttpEndpoint.createRecord(name, host, port, root,
                new JsonObject().put("api.name", config().getString("api.name", ""))
        );
        return publish(record);
    }

    /**
     * Publish a service with record.
     *
     * @param record service record
     * @return async result
     */
    private Future<Void> publish(Record record){
        if(discovery==null){
            try {
                start();
            }catch (Exception e){
                throw new IllegalStateException("Cannot create mytest.discovery service");
            }
        }
        Future<Void> future =  Future.future();
        discovery.publish(record,ar->{
            if(ar.succeeded()){
                registeredRecords.add(record);
                logger.info("Service <" + ar.result().getName() + "> published");
                future.complete();
            }
            else {
                future.fail(ar.cause());
            }
        });
        return future;
    }

    //重写服务发现类
    @Override
    public void start() throws Exception {
        discovery = ServiceDiscovery.create(getVertx(), new ServiceDiscoveryOptions().setAnnounceAddress("service-announce").setName("my-name"));
        //create a new custom record
        //publishHttpEndpoint("my-service","localhost",8082,"/");
        publishHttpEndpoint("some-rest-api","localhost",8082,"/");
        publishHttpEndpoint("some-rest-api","localhost",8083,"/");

    }

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        vertx.deployVerticle(ServiceDiscoveryVerticle.class.getName());
    }



}
